package com.ncloud.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.aaaa.service.UserService;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsCust;
import com.ncloud.crm.entity.order.Order;
import com.ncloud.crm.entity.order.OrderCustomer;
import com.ncloud.crm.mapper.OrderCustomerMapper;
import com.ncloud.crm.service.BsCustService;
import com.ncloud.crm.service.OrderCustomerService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;
import com.ncloud.crm.utils.Utility;
import com.ncloud.param.service.SequenceService;

@Service
public class OrderCustomerServiceImpl implements OrderCustomerService {
	
	private static final Logger logger = LogManager.getLogger(OrderCustomerServiceImpl.class);
	
	@Autowired
	private OrderCustomerMapper orderCustomerMapper;
	@Autowired
	private BsCustService bsCustService;
	@Reference
	private SequenceService sequenceService;
	@Reference
	private UserService userService;
	public List<OrderCustomer> getByOrderId(Long orderId) {
		List<OrderCustomer> orderCustomers = orderCustomerMapper.getByOrderId(orderId);
		return orderCustomers;
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}
	@Transactional
	@Override
	public JSONObject insert(JSONObject json) {

		OrderCustomer orderCustomer = JSON.parseObject(json.toJSONString(),OrderCustomer.class);
		try {
			validation(orderCustomer);
			/*客户*/
			orderCustomerMapper.insertOrderCustomer(orderCustomer);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}


	private void validation(OrderCustomer cust){
		if(cust.getCustId() == null ){
			Long id = sequenceService.getSequence("seq_cust_id_seq");
			cust.setCustId(id);
		}
	}

	@Override
	public JSONObject validate(JSONObject json, JSONObject result) {
		JSONObject resultJson = new JSONObject();
		JSONObject jsonObject = new JSONObject();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		if(json.containsKey(OrderNodeDefineUtils.ORDER_CUSTOMER)){
			jsonObject = json.getJSONObject(OrderNodeDefineUtils.ORDER_CUSTOMER);
			/*if(!jsonObject.containsKey("companyCode")){
				throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"companyCode 信息不存在！");
			}*/
			String modifyTag = jsonObject.getString("modifyTag");
			if(StringUtils.isEmpty(modifyTag)){
				throw new UserException(ResultEnum.PARAM_ERROR);
			}
			/*生成orderId*/
			if(!jsonObject.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(jsonObject.getString(TableIdDefineUtils.ORDER_ID))) {
				if (!result.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.ORDER_ID))) {
					throw new UserException(ResultEnum.PARAM_ERROR.getCode(), "订单客户信息orderId不存在！");
				} else {
					jsonObject.put(TableIdDefineUtils.ORDER_ID, result.getString(TableIdDefineUtils.ORDER_ID));
				}
			}
			/*处理custId*/
			if(!jsonObject.containsKey(TableIdDefineUtils.CUST_ID) || StringUtils.isEmpty(jsonObject.getString(TableIdDefineUtils.CUST_ID))){
				if(modifyTag.equals(Constant.ADD)){
					/*if(getCustId(jsonObject.getString("companyCode")) != null){
						jsonObject.put("modifyTag",Constant.NO_CHANGE);
					}*/
					if(!result.containsKey(TableIdDefineUtils.CUST_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.CUST_ID))){
						throw new UserException(ResultEnum.PARAM_ERROR.getCode(), "订单客户信息custId不存在！");
					}else{
						jsonObject.put(TableIdDefineUtils.CUST_ID,result.getString(TableIdDefineUtils.CUST_ID));
					}
					//创建客户账号
					String account = jsonObject.getString("contactEmail");
					Long num = userService.isUserAccount(account);
					if(num ==null || num <=0){
						String pwd = Utility.getRandomString(Constant.CUST_PASSWD_LENGTH);
						JSONObject obj = new JSONObject();
						obj.put("account", account);
						obj.put("pwd", pwd);
						obj.put("userType", Constant.USER_TYPE_CUST);
						obj.put("name", jsonObject.getString("custName"));
						obj.put("email", jsonObject.getString("contactEmail"));
						obj.put("mobile", jsonObject.getString("contactPhone"));
						obj.put("telephone", jsonObject.getString("contactPhone"));
						obj.put("custId", jsonObject.getLong(TableIdDefineUtils.CUST_ID));
						resultJson.put(OrderNodeDefineUtils.USER_INFO,obj);
					/*处理邮件*/
						JSONObject email = new JSONObject();
						email.put("sysCode", "CRM");
						email.put("msgTo", account);
						email.put("subject", "账号开通通知");
						email.put("bcc","shiq@btte.net");
						JSONObject content = new JSONObject();
						content.put("custName", jsonObject.getString("custName"));
						content.put("account", account);
						content.put("pwd", pwd);
						email.put("content", content);
						email.put("templateName", "custCreateUser.ftl");
						email.put("msgType", "1");
						//email.put("msgCode","A");//初始状态，不做处理
						resultJson.put(OrderNodeDefineUtils.USER_EMAIL,email);
					}
				}else{
					throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单客户信息custId不存在！");
				}
			}
			//
			result.put("custName",jsonObject.getString("custName"));
			//设置人员
			jsonObject.put("createUser",json.getLong("userId"));
			//设置创建时间
			jsonObject.put("createTime", result.getString("createTime")!=null?result.getString("createTime"):DateUtils.getDateTime());
			/*保存客户信息*/
			resultJson.put(OrderNodeDefineUtils.ORDER_CUSTOMER,jsonObject);
		}
		logger.info("订单客户信息:{}"+jsonObject.toJSONString());
		return resultJson;
	}

	@Override
	public OrderCustomer getByCompanyCode(String companyCode) {
		return orderCustomerMapper.getByCompanyCode(companyCode);
	}
	/*根据统一公司编码查询客户信息*/
	@Override
	public Long getCustId(String companyCode){
		Long custId = null;
		BsCust bsCust = bsCustService.getByCompanyCode(companyCode);
		if(bsCust != null && bsCust.getCustId() != null){
			return bsCust.getCustId();
		}else{
			OrderCustomer orderCustomer = orderCustomerMapper.getByCompanyCode(companyCode);
			if(orderCustomer != null && orderCustomer.getCustId() != null){
				return orderCustomer.getCustId();
			}else {
				return custId;
			}
		}
	}

	@Override
	public List<OrderCustomer> getCustByEmail(String email) {
		return orderCustomerMapper.getCustByEmail(email);
	}

	@Override
	public OrderCustomer getNewCustomerByOrder(Order order) {
		OrderCustomer orderCust = new OrderCustomer(); 
		List<OrderCustomer> orderCusts = this.getByOrderId(order.getOrderId());
		orderCusts.removeIf(x->Constant.DEL.equals(x.getModifyTag()));
		
		if(orderCusts.isEmpty()){
			BsCust cust = bsCustService.getCustInfoById(order.getCustId());
			BeanUtils.copyProperties(cust, orderCust);
		}else{
			orderCust = orderCusts.get(0);
		}
		
		return orderCust;
	}

	@Override
	public JSONObject getCustInfoByCustId(Long custId) {
		List<OrderCustomer> customers = orderCustomerMapper.getByCustId(custId);
		if(customers!=null&&customers.size()>0)
			return JSON.parseObject(JSON.toJSONString(customers.get(0)));
		return null;
	}
}
